﻿///////////////////////////////////////////////////////////////////////////////
/* Code Usage: This code is referenced from
 *  http://blog.slaven.net.au/archives/2008/03/16/comparing-two-arrays-or-ienumerables-in-c/
*/
///////////////////////////////////////////////////////////////////////////////

using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace ComputationalGeometry.DataStructures
{
    public static class CollectionUtility
    {
        public static bool IsEqualTo<TSource>(this IEnumerable<TSource> value, IEnumerable<TSource> compareList, IEqualityComparer<TSource> comparer)
        {
            if (value == compareList)
            {
                return true;
            }

            if (value == null || compareList == null)
            {
                return false;
            }

            if (comparer == null)
            {
                comparer = EqualityComparer<TSource>.Default;
            }

            IEnumerator<TSource> enumerator1 = value.GetEnumerator();
            IEnumerator<TSource> enumerator2 = compareList.GetEnumerator();

            bool enum1HasValue = enumerator1.MoveNext();
            bool enum2HasValue = enumerator2.MoveNext();

            try
            {
                while (enum1HasValue && enum2HasValue)
                {
                    if (!comparer.Equals(enumerator1.Current, enumerator2.Current))
                    {
                        return false;
                    }

                    enum1HasValue = enumerator1.MoveNext();
                    enum2HasValue = enumerator2.MoveNext();
                }

                return !(enum1HasValue || enum2HasValue);
            }
            finally
            {
                enumerator1.Dispose();
                enumerator2.Dispose();
            }
        }

        public static bool IsEqualTo<TSource>(this IEnumerable<TSource> value, IEnumerable<TSource> compareList)
        {
            return IsEqualTo(value, compareList, null);
        }

        public static bool IsEqualTo(this IEnumerable value, IEnumerable compareList)
        {
            return IsEqualTo<object>(value.OfType<object>(), compareList.OfType<object>());
        }
    }
}

